#---------------------------------------------------
#	
#		构建一个公用的	Makefile		模板	  
#
#---------------------------------------------------

ifeq ("$(origin V)", "command line")
BUILD_DIR := $(V)
endif

SEL_ARM_COMPILER = 1

#编译链选项
ifdef SEL_ARM_COMPILER
	CROSS_COMPILER	:= arm-buildroot-linux-gnueabihf-
	COMPILER := $(CROSS_COMPILER)gcc
	LINKER   := $(CROSS_COMPILER)gcc
	ARCHIVE  := $(CROSS_COMPILER)ar
else
	COMPILER ?= gcc
	LINKER   ?= gcc
	ARCHIVE  ?= ar
endif

STD ?= gnu99

CC = $(COMPILER)
LD = $(LINKER)
SHELL = /bin/sh
removeSpaces = $(subst \ ,+SL5C20+,$1)
restoreSpaces = $(subst +SL5C20+,\ ,$1)

#头文件路径
INCLUDE = -I./ \
	-I./src		\
	-I./include	\
	-I./my_thread \
	-I./pro_logs \
	-I./dbg \
	-I./msg_sort_proc \
\

APP_BUILDER_OUTPUT_DIRECTORY=.

#编译参数
COMPILER_FLAGS ?= \
	-Wall \
	-ggdb \
	-O0   \
	-std=$(STD) \
	-g3
					   
APPLICATION_FILES= \
	./src/main.c \
	./my_thread/my_thread.c \
	./pro_logs/my_log.c \
	./dbg/dbg_trace.c \
	./msg_sort_proc/msg_sort_process.c \

APPLICATION_FILES:=$(call removeSpaces, $(APPLICATION_FILES))

LIBRARIES = \
 \
 
OUTPUT_DIR=$(APP_BUILDER_OUTPUT_DIRECTORY)/output
OUTPUT_DIR_CREATED= $(OUTPUT_DIR)/created
EXE_DIR= $(OUTPUT_DIR)

APPLICATION_OBJECTS= $(addprefix $(OUTPUT_DIR)/, $(notdir $(APPLICATION_FILES:.c=.o)))

TARGET_FILE= $(EXE_DIR)/test

DEPENDENCY_FLAGS ?= -MMD -MP -MF $(@D)/$(@F:.o=.d)

DEPENDENCY_POST_PROCESS ?=

CPPFLAGS= $(INCLUDE) $(COMPILER_FLAGS) $(DEPENDENCY_FLAGS)
LINKER_FLAGS ?= 
	CPPFLAGS += -DNO_READLINE

LINKER_FLAGS += \
	-lpthread
	
.PHONY:all
all: $(TARGET_FILE)
	@echo $(origin V)
	@echo $(BUILD_DIR)
	
ifneq ($(MAKECMDGOALS),clean)
-include $(APPLICATION_OBJECTS:.o=.d)
endif

$(TARGET_FILE): $(APPLICATION_OBJECTS) $(LIBRARIES)
	@echo "---------------------------- Start Compiler ----------------------------"
	$(LD) $^ $(LINKER_FLAGS) -o $(TARGET_FILE)
	@mv $(TARGET_FILE) ./
	@echo -e '\n$@ build success'
	@echo "---------------------------- Endt Compiler ----------------------------"
	
.PHONY:clean
clean:
	rm -rf $(OUTPUT_DIR) test
	@echo "---------------CLEAN END---------------"

$(OUTPUT_DIR_CREATED):
	mkdir -p $(OUTPUT_DIR)
	mkdir -p $(EXE_DIR)
	touch $(OUTPUT_DIR_CREATED)
	
define create-build-rules 
$(OUTPUT_DIR)/$(notdir $(1:%.c=%.o)): $(call restoreSpaces, $1) | $(OUTPUT_DIR_CREATED) 
	$$(CC) $$(CPPFLAGS) -c "$$<" -o $$@
	$$(DEPENDENCY_POST_PROCESS)
endef 

$(foreach d, $(APPLICATION_FILES), $(eval $(call create-build-rules,$d))) 




	
